<?php
  session_start();

  date_default_timezone_set('Europe/London');
 
  function __autoload($class_name) {
      require_once ('classes/' . $class_name . '.class.php');
  }
  
  include "include/sitefunctions.php";
  include "include/lobbyfunctions.php";
  
  define(SITE_DEBUGGING, true);
  set_error_handler("siteError");
  
  $db = new DbConnection();
  
  if (isset($_GET['logout'])) {
    postMessage($db, "system", $_SESSION['username'] . " has logged out", date('H:i:s'));
    $db->dbUpdate("UPDATE lobbyusers SET `loggedon`='0' WHERE `username`='".$_SESSION['username']."'");
    removePlayerFromGames($db, $_SESSION['username']);
    debug("User ". $_SESSION['username'] ." logged off");
    $_SESSION['username'] = "";
    $_SESSION['area'] = "";
    $_SESSION['ingame'] = "";
    unset($_SESSION['username']);
    unset($_SESSION['area']);
    unset($_SESSION['ingame']);
    debug("Logged out");
    //header('Location: index.php');
  }  
  
  // Some defaults
  $username = "";
  $_SESSION['area'] = 'login';
  
  if (isset($_POST['username'])) {
    $username = $_POST['username'];
    $_SESSION['username'] = $username;
    debug("Found user ". $username ." in _POST");
    postMessage($db, "system", $_SESSION['username'] . " has logged in", date('H:i:s')); 
  } else if (isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
    debug("Found user ". $username ." in _SESSION");
  } else if (isset($_COOKIE['username'])) {
    $username = $_COOKIE['username'];
    debug("Found user ". $username ." in _COOKIE");
  }
  
  if (isValidUsername($username)) {
    $_SESSION['area'] = 'lobby';
    
    debug("In the lobby");
    
    // check the Database  
    $result = $db->dbSelect("SELECT * FROM lobbyusers WHERE `username`='$username'");
          
    if ($result) {
      $userDetails = mysql_fetch_array( $result  );
      if ($userDetails['username'] == $username) {
        if ($userDetails['ip'] == $_SERVER['REMOTE_ADDR']) {
          // IP is the same, alls well...
          $logonTime = date('Y-m-d H:i:s');
          $db->dbUpdate("UPDATE lobbyusers SET `loggedon`='1', `lastactive`='".$logonTime ."' WHERE `username`='".$_SESSION['username']."' LIMIT 1");
          //
          debug("User ". $username ." found in database");
        } else {
          // IP is different, maybe different person, or not... has to be inactive for 3hrs
          $lastActive = strtotime($userDetails['lastactive']);
          $allowedTime = 60 * 60 * 3; // Thats 3hrs in seconds!
          if ($lastActive > (time() - $allowedTime)) {
            $error = "Unable to reasign username, user last active at: ".$userDetails['lastactive'];
            debug($error);
            // Unset the username
            unset($_SESSION['username']);
            $_SESSION['area'] = 'login';
          } else {
            $logonTime = date('Y-m-d H:i:s');
            $db->dbUpdate("UPDATE lobbyusers SET `loggedon`='1', `lastactive`='".$logonTime."', `ip`='".$_SERVER['REMOTE_ADDR']."', `posts`='0' WHERE `username`='".$_SESSION['username']."' LIMIT 1");
            postMessage($db, "system", $_SESSION['username'] . " has logged in", $logonTime);
            debug("User ". $username ." found in database (reasigned)");
          }
        }
      } else {
        saveNewUser(&$db, $username);
        debug("Not found, new user saved");
      }
    } else {
      saveNewUser(&$db, $username);
      debug("No results, new user saved");
    }
  } else {
    $_SESSION['area'] = 'login';
    
  }
  
  ///Done all the user stuff; how about a game!?
  if (isset($_POST['createGame'])) {
    if (isset($_SESSION['ingame']) != true) {
      debug("creating Game");
      
      $gameName = $_POST['gameName'];
      $players = $_POST['players'];
      
      $db->dbInsert("INSERT INTO games (`id`, `name`, `player1`, `player2`, `player3`, `player4`, `maxplayers`, `map`, `inprogress`, `created`)
        VALUES (
        NULL,
        '".$gameName."',
        '".$_SESSION['username']."',
        '-',
        '-',
        '-',
        '".$players."',
        'Default',
        '0',
        '".date('Y-m-d H:i:s')."')");
      
      postMessage($db, "system", $_SESSION['username'] . " has created a game", date('H:i:s'));
      
      $result = $db->dbSelect("SELECT id, name, player1 FROM games WHERE name='".$gameName."' AND player1='".$_SESSION['username']."'");
      if ($result) {
        $gameDetails = mysql_fetch_array($result);
        if ($gameDetails) {
          $_SESSION['ingame'] = $gameDetails['id'];
          $_SESSION['host'] = true;
        }
      }
    }
  }

  if (isset($_GET['area'])) {
    $toArea = $_GET['area'];
    if ($toArea == 'rules' || $toArea == 'gallery') {
      $_SESSION['area'] = $toArea;
    }
  }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
      @import url('css/styles.css');
    </style>
    <title>Boardwinia!</title>
    <meta name="description" content=""/>

    <meta name="author" content="ImmortalNights"/>
    <meta name="copyright" content=""/>
    <meta name="keywords" content=""/>

    <meta name="robots" content="index,follow" />
    
    <script type="text/javascript" src="js/content.js"></script>
    <?php if ($_SESSION['area'] =='lobby') {
      echo '<script type="text/javascript" src="js/lobby.js"></script>';
    } ?>
    <link rel="shortcut icon" href="favicon.ico" />
  </head>
  <body>
    <div class="header">
    </div>
    
    <div id="content">
      <?php require_once('content/' . $_SESSION['area'] . '.area.php'); ?>
    </div>
    
    <div id="footer">
    </div>
    
    
    <?php
      outputDebug();
    ?>
  </body>
</html>

